package mn.idax.exchange.otc.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mn.idax.exchange.auth.bean.AuthInfo;
import mn.idax.exchange.auth.util.AuthInfoUtils;
import mn.idax.exchange.common.bean.ResponseData;
import mn.idax.exchange.otc.constant.CommonConstant;
import mn.idax.exchange.otc.domain.OrderPageParamsSeniorDTO;
import mn.idax.exchange.otc.domain.OrderShowResultDTO;
import mn.idax.exchange.otc.enums.LogOrderProcessEnum;
import mn.idax.exchange.otc.enums.response.OTCAdResponseEnum;
import mn.idax.exchange.otc.exception.IdaxException;
import mn.idax.exchange.otc.service.BusinessApplyService;
import mn.idax.exchange.otc.service.OTCAdsService;
import mn.idax.exchange.otc.service.OTCOrderService;
import mn.idax.exchange.otc.util.DateUtils;
import mn.idax.exchange.otc.util.function.OrderProcessLogFunction;
import mn.idax.exchange.otc.vo.OrderExcelDTO;
import mn.idax.exchange.otc.vo.OrderPageDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Create by jack_huang on 2018/11/19
 */
@Api(value = "订单v2接口",tags={"订单v2接口"})
@RestController
@RequestMapping("/api/v2/order")
public class OrderSecController {

    @Autowired
    private OTCOrderService otcOrderService;

    @Autowired
    private OTCAdsService otcAdsService;

    @Autowired
    private BusinessApplyService businessApplyService;


    @PostMapping("/getOrderList")
    @ApiOperation(value = "订单列表展示", notes = "需传入查询参数（JSON），(jack_huang，自测通过)")
    public ResponseData getOrderList(@RequestBody OrderPageParamsSeniorDTO pageParams) {

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        //参数封装
        OrderPageDTO orderPageDTO = makeOrderPageParams(pageParams,userId);
        //查询
        OrderShowResultDTO orderList = new OrderShowResultDTO();
        OrderProcessLogFunction.logOrderProcess(s -> {
            OrderShowResultDTO orderResult = otcOrderService.getOrderPage(orderPageDTO);
            BeanUtils.copyProperties(orderResult , orderList);
        }, this.getClass() , LogOrderProcessEnum.order_query.getMessage());

        /**
         * 0 普通用户
         * 1 承兑商（卖家）
         */
        if (businessApplyService.isbusinesser(userId) < 1) {
            orderList.setIsBusiness(0);
        }else{
            orderList.setIsBusiness(1);
        }

        return ResponseData.success(orderList);
    }

    private OrderPageDTO makeOrderPageParams(OrderPageParamsSeniorDTO pageParams, Integer userId) {
        Integer pageIndex = pageParams.getPageIndex();
        Integer pageSize = pageParams.getPageSize();

        if (pageIndex == null || pageIndex < 0 ) {
            pageIndex = 0;
        }
        //防止用户恶意攻击
        if (pageSize == null || pageSize <= 0 || pageSize > 1000) {
            pageSize = 1000;
        }
        String startTime=null;
        String endTime=null;

        if (!StringUtils.isEmpty(pageParams.getStartTime())){
            startTime =  DateUtils.getStartTime(pageParams.getStartTime());
        }

        if (!StringUtils.isEmpty(pageParams.getEndTime())){
            endTime =  DateUtils.getEndTime(pageParams.getEndTime());
        }

        Integer orderState = pageParams.getOrderState();

        String status = null;
        if (orderState == null){
            orderState = null;
        } else if (orderState == 1){
            status = CommonConstant.STATE_ONE;
            orderState = 1;
        } else if (orderState == 2){
            status = CommonConstant.STATE_TWO;
            orderState = 4;
        } else {
            status = CommonConstant.STATE_THREE;
            orderState = 5;
        }
        if(pageParams.getOrderType() == null || pageParams.getOrderType() ==3){
            pageParams.setOrderType(null);
        }

        return new OrderPageDTO(userId, pageParams.getOrderNum(), pageParams.getOrderType(), orderState,
                status,pageParams.getPair(), pageIndex, pageSize, startTime, endTime);

    }


    @PostMapping("/exportMyOrder")
    @ApiOperation(value = "导出我的订单",notes = "说明：<br/>1.需传入查询参数（JSON） <br/>2.导出需用户登录【jack_huang/自测通过】")
    public ResponseData export(@RequestBody OrderPageParamsSeniorDTO pageParams) throws IOException {

        //获取登录用户信息
        AuthInfo authInfo = AuthInfoUtils.getCurrent();
        Integer userId = Optional.ofNullable(authInfo).map(a -> a.getId()).orElse(-1);
        //参数封装
        OrderPageDTO orderPageDTO = makeOrderPageParams(pageParams,userId);
        //查询
        List<OrderExcelDTO> exportOrderPage = otcOrderService.queryExportData(orderPageDTO);
        return ResponseData.success(exportOrderPage);
    }


}
